package com.hspedu.reflection;

import com.hspedu.Cat;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author DL5O
 * @version 1.0
 * 测试反射调用的性能，和优化方案
 */
public class Reflection02 {
    public static void main(String[] args) throws Exception {
        m1();
        m2();
        m3();
    }

    @Test
    //使用传统方法来调用hi
    public static void m1() {
        Cat cat = new Cat();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 999999; i++) {
            cat.hi();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("传统方法 耗时:" + (endTime - startTime));
    }

    @Test
    //反射机制调用hi
    public static void m2() throws Exception {
        Properties properties = new Properties();
        String filePath = "src\\re.properties";

        properties.load(new FileReader(filePath));
        String classFullPath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");

        Class cls = Class.forName(classFullPath);
        Object o = cls.newInstance();
        Method method1 = cls.getMethod(method);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 999999; i++) {
            method1.invoke(o);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射机制 耗时:" + (endTime - startTime));
    }

    //反射调用优化 + 关闭访问检查
    public static void m3() throws Exception {
        Properties properties = new Properties();
        String filePath = "src\\re.properties";

        properties.load(new FileReader(filePath));
        String classFullPath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");

        Class cls = Class.forName(classFullPath);
        Object o = cls.newInstance();
        Method method1 = cls.getMethod(method);
        method1.setAccessible(true);//在调用方法时,关闭访问检查
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 999999; i++) {
            method1.invoke(o);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射机制 耗时:" + (endTime - startTime));
    }
}
